package com.ease.database.initializer;

import java.util.List;
import java.util.Map;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.util.StringUtils;

import com.ease.common.util.Detect;
import com.ease.common.util.FileUtil;
import com.ease.common.util.StringWidthUtil;
import com.ease.common.vo.MapParameter;
import com.ease.dao.JdbcTemplateDataAccessObject;
import com.obas.test.ApplicationContextUserContextTest;

/**
 * @author nathanleewei
 * 
 */
public class AppIdInitializer extends ApplicationContextUserContextTest {

	@Autowired
	JdbcTemplateDataAccessObject jdbcTemplateDataAccessObject;

	@Test
	public void test() {
		

		jdbcTemplateDataAccessObject.remove("DELETE FROM M_BUSINESSAPPLICATION", (SqlParameterSource)null);

		jdbcTemplateDataAccessObject.remove("DELETE FROM M_BUSINESSSERVING", (SqlParameterSource)null);
		
		jdbcTemplateDataAccessObject.remove("DELETE FROM I_DPI_APPID", (SqlParameterSource)null);		
		
		String string = FileUtil.readClassPathResourceToString(AppIdInitializer.class, "APPID_20130628_1714.txt");

		String[] rows = StringUtils.delimitedListToStringArray(string, "\r\n");
		MapParameter parameter = null;
		if (null != rows) {
			for (String row : rows) {
				String[] values = StringUtils.delimitedListToStringArray(row, "|");
				if (null == values || values.length < 4) {
					continue;
				}

				String appId = Detect.trim(values[0]);
				String appName = Detect.trim(values[1]);
				String serviceId = Detect.trim(values[2]);
				String description = Detect.trim(values[3]);

				parameter = new MapParameter();
				parameter.put("appId", appId);
				parameter.put("serviceId", serviceId);
				//
				List<Map<String, Object>> appids = jdbcTemplateDataAccessObject.find("SELECT * FROM I_DPI_APPID T WHERE T.APPID=:appId and T.SERVICEID=:serviceId ", parameter);
				if (!notEmpty(appids)) {
					parameter.put("appName", appName);
					if (null != description && description.startsWith("\"")) {
						description = description.substring(1);
						description = StringWidthUtil.asHalfWidth(description);
					}
					parameter.put("description", description);
					jdbcTemplateDataAccessObject.create("INSERT INTO I_DPI_APPID(APPID, APPNAME, SERVICEID, DESCRIPTION)VALUES(:appId, :appName, :serviceId, :description)", parameter);
				}
			}
		}
	}
}
